/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.tms.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.infor.entity.Goods;
import com.jeeplus.modules.infor.service.GoodsService;
import com.jeeplus.modules.tms.entity.*;
import com.jeeplus.modules.tms.service.NotnodeService;
import com.jeeplus.modules.tms.service.ReceiptService;
import com.jeeplus.modules.tms.service.TmsWaybillService;
import com.jeeplus.modules.wms.util.CopyUtil;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.tms.service.TailAfterService;

/**
 * 在途跟踪Controller
 * @author 李超辉
 * @version 2017-12-07
 */
@Controller
@RequestMapping(value = "${adminPath}/tms/tailAfter")
public class TailAfterController extends BaseController {

	@Autowired
	private TailAfterService tailAfterService;
	@Autowired
	private NotnodeService notnodeService;
	@Autowired
	private TmsWaybillService waybillService;
	@Autowired
	private ReceiptService receiptService;
	@Autowired
	private GoodsService goodsService;
	
	@ModelAttribute
	public TailAfter get(@RequestParam(required=false) String id) {
		TailAfter entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = tailAfterService.get(id);
		}
		if (entity == null){
			entity = new TailAfter();
		}
		return entity;
	}
	
	/**
	 * 在途跟踪列表页面
	 */
	@RequiresPermissions("tms:tailAfter:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/tms/tailAfterList";
	}
	
		/**
	 * 在途跟踪列表数据
	 */
	@ResponseBody
	@RequiresPermissions("tms:tailAfter:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(TailAfter tailAfter, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<TailAfter> page = tailAfterService.findPage(new Page<TailAfter>(request, response), tailAfter); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑在途跟踪表单页面
	 */
	@RequiresPermissions(value={"tms:tailAfter:view","tms:tailAfter:add","tms:tailAfter:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(TailAfter tailAfter,String i, Model model) {
		TmsWaybill bill=waybillService.get(i);
		model.addAttribute("tmsWaybill", bill);
		TailAfter t=tailAfterService.findUniqueByProperty("bill",i);
		if(t!=null){
			model.addAttribute("tailAfter", t);
		}else{
			tailAfter.setBill(i);
			model.addAttribute("tailAfter", tailAfter);}

		Notnode n=new Notnode();
		n.setBill(i);
		List<Notnode> list=notnodeService.findList(n);
		model.addAttribute("notnode", list);

		return "modules/tms/tailAfterForm";
	}

	/**
	 * 查看，增加，编辑在途跟踪表单页面(快捷流程)
	 */
	@RequiresPermissions(value={"tms:tailAfter:view","tms:tailAfter:add","tms:tailAfter:edit"},logical=Logical.OR)
	@RequestMapping(value = "form1")
	public String form1(TailAfter tailAfter,String i, Model model) {
		TmsWaybill bill=waybillService.get(i);
		Kj kj=new Kj();
		int a=0;
		List<TmsMaterialsInformation> l=bill.getTmsMaterialsInformationList();
		for(TmsMaterialsInformation t:l){
			int amount=Integer.parseInt(t.getLoadingQuantity());
			Goods g=goodsService.get(t.getName().getId());
			int bl=Integer.parseInt(g.getProportion());
			int c=amount/bl;
			a+=c;
		}
		kj.setClienteleEntruckingNumber(a+"");
		kj.setCompanyEntruckingNumber(a+"");
		kj.setShipperEntruckingNumber(a+"");
		model.addAttribute("tmsWaybill", bill);

		kj.setBill(bill.getId());
		model.addAttribute("kj", kj);
		Notnode n=new Notnode();
		n.setBill(i);
		List<Notnode> list=notnodeService.findList(n);
		model.addAttribute("notnode", list);

		return "modules/tms/2/tailAfterForm";
	}


	@ResponseBody
	@RequestMapping(value = "save2")
	public AjaxJson save2(Kj kj,HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if(kj.getThArrivalTime()==null||kj.getThDepartureTime()==null){
			j.setSuccess(false);
			j.setMsg("请检查确定无误后保存！");
			return j;
		}
		if(kj.getClienteleCollectState().length()<1||kj.getClienteleCollectName().length()<1){
			j.setSuccess(false);
			j.setMsg("请检查确定无误后保存！");
			return j;
		}
		TailAfter t= new TailAfter();
		t= (TailAfter) CopyUtil.Copy(t,kj,false);
		tailAfterService.save(t);
		Receipt r=new Receipt();
		r= (Receipt) CopyUtil.Copy(r,kj,false);
		receiptService.save(r);
		TmsWaybill tw=waybillService.get(r.getBill());
		if(r.getCompanyCollectName()!=null&r.getCompanyCollectName().length()>0){
			tw.setStatus("已回单");
		}
		if(r.getClienteleCollectState().equals("异常")||r.getCompanyCollectState().equals("异常")||r.getShipperCollectState().equals("异常")){
			tw.setZt("异常");
		}else{
			tw.setZt("正常");
		}

		tw.setBillStatus("已签收");
		waybillService.save(tw);

		j.setSuccess(true);
		j.setMsg("保存成功");
	return j;}
	/**
	 * 保存在途跟踪
	 */
	@ResponseBody
	@RequiresPermissions(value={"tms:tailAfter:add","tms:tailAfter:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(TailAfter tailAfter,HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, tailAfter)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
        String id=request.getParameter("scId");
		if(id!=null&&id!=""){
			String[] ids=id.split(",");
			for(String i:ids){
				notnodeService.delete(notnodeService.get(i));
			}
		}
		tailAfterService.save(tailAfter);//新建或者编辑保存
		TmsWaybill t=waybillService.get(tailAfter.getBill());
		t.setBillStatus("在途");
		waybillService.save(t);
		j.setSuccess(true);
		j.setMsg("保存在途跟踪成功");
		return j;
	}
	
	/**
	 * 删除在途跟踪
	 */
	@ResponseBody
	@RequiresPermissions("tms:tailAfter:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(TailAfter tailAfter, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		tailAfterService.delete(tailAfter);
		j.setMsg("删除在途跟踪成功");
		return j;
	}
	
	/**
	 * 批量删除在途跟踪
	 */
	@ResponseBody
	@RequiresPermissions("tms:tailAfter:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			tailAfterService.delete(tailAfterService.get(id));
		}
		j.setMsg("删除在途跟踪成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("tms:tailAfter:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(TailAfter tailAfter, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "在途跟踪"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<TailAfter> page = tailAfterService.findPage(new Page<TailAfter>(request, response, -1), tailAfter);
    		new ExportExcel("在途跟踪", TailAfter.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出在途跟踪记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("tms:tailAfter:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<TailAfter> list = ei.getDataList(TailAfter.class);
			for (TailAfter tailAfter : list){
				try{
					tailAfterService.save(tailAfter);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条在途跟踪记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条在途跟踪记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入在途跟踪失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tms/tailAfter/?repage";
    }
	
	/**
	 * 下载导入在途跟踪数据模板
	 */
	@RequiresPermissions("tms:tailAfter:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "在途跟踪数据导入模板.xlsx";
    		List<TailAfter> list = Lists.newArrayList(); 
    		new ExportExcel("在途跟踪数据", TailAfter.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tms/tailAfter/?repage";
    }

}